package routers

import (
	"GoIris/db"
	"GoIris/filechain"
	"GoIris/session"
	"fmt"
	"github.com/kataras/iris"
	"github.com/kataras/iris/core/router"
	"github.com/kataras/iris/sessions"
	"time"
)

var (
	cookieNameForSessionID = "mycookiesessionnameid"
	sess                   = sessions.New(sessions.Config{Cookie: cookieNameForSessionID})
)

//存入数据库，需要检测更新
var sessionMap = make(map[string]string)
var chain = make([][]string, 1)
var TempMap = make(map[int]map[string]interface{})

//用户处理链
var request = make(map[string]map[string]string)

//应用路由

func ViewRouter(api router.Party) {
	fmt.Println("进入程序")
	//连接数据库
	DB, err := db.ConnectDB()
	if err != nil {
		fmt.Printf("连接失败 %v", err)
	}
	//生成db操作对象
	user := db.NewUser()
	//生成fileChain操作对象
	btc := filechain.BlockBuild()
	//从数据库拉取最后一个区块
	/*contents := map[string]string{
		"email": "Hello World!",
	}
	_, block := btc.CreateBlock(0, "001", contents)*/
	index, block := user.QueryBlock(DB)
	fmt.Printf("------------>%s \n ", block)
	chain[len(chain)-1] = block
	fmt.Println("启动长度", index+len(chain))

	////
	// start page
	////
	api.Get("/n", func(ctx iris.Context) {
		fmt.Println("---->")
		id := session.Login(ctx)
		//ctx.WriteString("Hello word")
		ctx.JSON(iris.Map{"name": sessionMap[id]})
	})
	////
	// 数据请求路由 ---> pages1.vue
	////
	api.Post("/showMdData", func(ctx iris.Context) {
		Index := ctx.FormValue("Index")
		id := session.Login(ctx)
		var tempSelectMap = make(map[string]string)
		tempSelectMap["index"] = Index
		request[sessionMap[id]] = tempSelectMap
		fmt.Println("showMdData -----> user select index =", request[sessionMap[id]]["index"])
	})

	///
	//userData ---> pages1.vue
	///
	api.Post("/userData", func(ctx iris.Context) {
		email := ctx.FormValue("email")
		json := user.QueryUserDate(DB, email)
		ctx.JSON(json)
	})
	///
	//showDataSelect ---> showMD.vue
	///
	api.Post("/showDataSelect", func(ctx iris.Context) {
		id := session.Login(ctx)
		TempData := ctx.FormValue("Index")
		fmt.Println(TempData)
		//查询数据库
		content := user.QueryContent(DB, request[sessionMap[id]]["index"])
		fmt.Println("从数据库读出的值 ----->", content)
		ctx.JSON(iris.Map{"IndexData": content})
	})

	////
	//验证登录
	////
	api.Post("/login", func(ctx iris.Context) {
		email := ctx.FormValue("user")
		password := ctx.FormValue("password")
		id := session.Login(ctx) //调用session临时保存sessionID
		sessionMap[id] = email
		reallyPassword := user.QueryOne(DB, string(email))
		if password == reallyPassword {
			fmt.Println("登录成功")
			ctx.JSON(iris.Map{"isBtnLoading": true})
			fmt.Println("User&Password    --->   ", user, password)
			err := ctx.View("MainPage.html")
			if err != nil {
				fmt.Println(err)
			}
		} else {
			fmt.Println("登录失败")
			ctx.JSON(iris.Map{"isBtnLoading": false})
			ctx.WriteString("密码错误")
		}
	})
	////
	//Markdown数据提交路由
	////
	api.Post("/data", func(ctx iris.Context) {
		//emailDB,TimestampDB,PreviousHashDB,ContentDB
		var indexID int
		var emailDB string
		var TimestampDB string
		var PreviousHashDB string
		var ContentDB string
		id := session.Login(ctx)
		data := ctx.FormValue("MarkDownData")
		fmt.Println(data)
		fmt.Println(sessionMap[id], data)
		content := map[string]interface{}{
			sessionMap[id]: data,
		}
		NowHash := btc.GetHash(chain)
		NowTime := fmt.Sprintf("%s", time.Now())
		_, block := btc.CreateBlock(index+len(chain), NowTime, NowHash, content)                                                               //创建区块DB ,user,
		chain, indexID, emailDB, TimestampDB, PreviousHashDB, ContentDB = btc.CreatChain(chain, block, TempMap, content, data, sessionMap[id]) //生成链
		user.InsertBlock(DB, indexID, emailDB, TimestampDB, PreviousHashDB, ContentDB)
		fmt.Println("现在的：", chain)
		fmt.Println("现在长度：", len(chain))
	})
	////
	// 访问User页面带数据
	////
	api.Get("/users.html", func(ctx iris.Context) {
		id := session.Login(ctx)
		ctx.ViewData("user", sessionMap[id])
		ctx.View("users.html")
	})
}
